import tkinter as tk
from tkinter import ttk
import os
import sys

# 元素周期表数据

def get_resource_path(relative_path):
        if hasattr(sys, '_MEIPASS'):
            return os.path.join(sys._MEIPASS, relative_path)
        return os.path.join(os.path.abspath("."), relative_path)

class PTableViewer:
    def __init__(self, root : tk.Tk):
        self.root = root
        self.root.title("PTableViewer v1.0.0")
        self.elementsList = self.elements_create(get_resource_path("data/elements.txt"))
        self.temp_elementsList = None
        self.create_widgets()

    
    def elements_create(self, paths):
        elements = []
        with open(paths, 'r', encoding="utf-8") as e:
            els = e.read().split(';')
            els.pop(-1)
            j = 0
            for i in range(len(els[0].split(','))):
                elements.append({"symbol": els[0].split(',')[i],
                                  "name": els[1].split(',')[i], 
                                  "atomic_mass": els[2].split(',')[i], 
                                  "number": els[3].split(',')[i], 
                                  "melting_point": els[4].split(',')[i], 
                                  "boiling_point": els[5].split(',')[i], 
                                  "ChineseName" : els[6].split(',')[i]})
        return elements
    
    def create_widgets(self):
        # 创建搜索界面
        self.search_frame = ttk.Frame(self.root, padding=(10, 10, 10, 10))
        self.search_frame.grid(row=0, column=0, padx=10, pady=10)
        
        # 创建搜索标签和输入框
        self.search_label = ttk.Label(self.search_frame, text="搜索:")
        self.search_label.pack(side=tk.LEFT)
        self.search_entry = ttk.Entry(self.search_frame, width=20)
        self.search_entry.pack(side=tk.LEFT)
        
        # 创建元素列表
        self.element_frame = ttk.Frame(self.root, padding=(10, 10, 10, 10))
        self.element_frame.grid(row=1, column=0, padx=10, pady=10)
        
        # 创建列表框和滚动条
        self.element_listbox = tk.Listbox(self.element_frame, width=20, height=20)
        self.element_listbox.pack(side=tk.LEFT, fill=tk.Y)
        
        self.scrollbar = ttk.Scrollbar(self.element_frame, orient=tk.VERTICAL, command=self.element_listbox.yview)
        self.scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        
        self.element_listbox.config(yscrollcommand=self.scrollbar.set)
        
        # 创建详细信息界面
        self.info_frame = ttk.Frame(self.root, padding=(10, 10, 10, 10))
        self.info_frame.grid(row=0, column=1, rowspan=2, padx=10, pady=10)
        
        # 创建详细信息标签
        self.element_info_label = ttk.Label(self.info_frame, text="选择一个元素查看详细信息，温度单位：摄氏度")
        self.element_info_label.pack()
        
        #标签按钮
        self.tag_entry = ttk.Entry(self.info_frame, width=20)
        self.tag_entry.pack()
        
        self.add_tag_button = ttk.Button(self.info_frame, text="添加标签", command=self.add_tag_to_element)
        self.add_tag_button.pack()
        
        # 绑定事件
        self.element_listbox.bind("<<ListboxSelect>>", self.show_element_info)
        self.search_entry.bind("<KeyRelease>", self.search_elements)
        
        # 初始加载所有元素
        self.load_elements(self.elementsList)
    
    def load_elements(self, elements):
        # 清空
        self.element_listbox.delete(0, tk.END)
        self.tag_entry.delete(0, tk.END)
        # 添加
        for element in elements:
            self.element_listbox.insert(tk.END, "{0} - {1}".format(element["symbol"], element["name"]))
    
    def search_elements(self, event):
        keyword = self.search_entry.get().lower()
    
    # 过滤
        filtered_elements = [element for element in self.elementsList
                            if (keyword in element["symbol"].lower() or
                                keyword in element["name"].lower() or
                                keyword in element["ChineseName"].lower() or
                                any(keyword in tag.lower() for tag in element.get("tags", [])))]
        self.temp_elementsList = filtered_elements
        
        # 更新列表显示
        self.load_elements(filtered_elements)
